import { createWebHashHistory, createRouter } from "vue-router";
import Register from "@/views/Register.vue";
import store from '../store'
import MainLayout from '@/layout/MainLayout.vue'

const routes = [
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Main.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/todo',
        name: 'Todo',
        component: () => import('../views/TodoList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'rest',
        name: 'RestArea',
        component: () => import('../views/RestArea.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'study',
        name: 'StudyArea',
        component: () => import('../views/StudyArea.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'activity',
        name: 'ActivityArea',
        component: () => import('../views/ActivityArea.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'team',
        name: 'TeamSprint',
        component: () => import('../views/TeamSprint.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'wall',
        name: 'RecordWall',
        component: () => import('../views/RecordWall.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'todos',
        name: 'TodoList',
        component: () => import('../views/TodoList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('../views/Statistics.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/team/:id',
        name: 'TeamDetail',
        component: () => import('@/views/TeamDetail.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/statistics',
        name: 'Statistics',
        component: () => import('@/views/Statistics.vue'),
        meta: { requiresAuth: true }
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isLoggedIn = !!localStorage.getItem('userId')
  if (requiresAuth && !isLoggedIn) {
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else if ((to.path === '/login' || to.path === '/register') && isLoggedIn) {
    next('/')
  } else {
    next()
  }
})

export default router;
